package rexsee.device;

import rexsee.core.browser.Browser;
import rexsee.core.browser.clazz.ActivityResult.ActivityResultListener;
import rexsee.core.browser.clazz.JavascriptInterface;
import rexsee.core.style.RexseeDrawable;
import rexsee.core.utilities.Utilities;
import android.app.Activity;
import android.app.WallpaperManager;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

public class RexseeWallpaper implements JavascriptInterface {

	public static final String INTERFACE_NAME = "Wallpaper";

	@Override
	public String getInterfaceName() {
		return mBrowser.application.resources.prefix + INTERFACE_NAME;
	}
	@Override
	public JavascriptInterface getInheritInterface(Browser childBrowser) {
		return this;
	}
	@Override
	public JavascriptInterface getNewInterface(Browser childBrowser) {
		return this;
	}

	private static final int WALLPAPER_WIDTH = 720;

	private final Browser mBrowser;

	public RexseeWallpaper(Browser browser) {
		mBrowser = browser;
	}

	//JavaScript Interface
	public boolean cropAndSet(String path) {
		return cropAndSet(path, null, null);
	}
	public boolean cropAndSet(String path, final String successAlert, final String failAlert) {
		if (!(Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()))) return false;
		Drawable drawable = RexseeDrawable.getDrawable(mBrowser, path, null);
		if (drawable == null) return false;
		String sdPath;
		if (path.toLowerCase().startsWith("file:///android_asset")) {
			int pos = path.lastIndexOf(".");
			if (pos < 0) return false;
			String ext = path.substring(pos);
			sdPath = "file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmpAssetImage" + ext;
			if (!Utilities.copyAssetToExternalStorage(mBrowser.getContext(), path.substring(22), sdPath)) return false;
			Utilities.scanMediaStore(mBrowser.getContext(), sdPath);
		} else {
			sdPath = path;
		}
		final String wallpaper = "file://" + Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmpWallpaper.png";
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(Uri.parse(sdPath), "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("scale", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", WALLPAPER_WIDTH);
		intent.putExtra("outputY", WALLPAPER_WIDTH);
		intent.putExtra("return-data", false); // true to return a Bitmap, false to directly save the cropped image  
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse(wallpaper)); //save output image in uri 
		mBrowser.activityResult.start(intent, new ActivityResultListener() {
			@Override
			public void run(int resultCode, Intent resultIntent) {
				if (resultCode == Activity.RESULT_OK && set(wallpaper)) {
					if (successAlert != null && !successAlert.trim().equals("")) {
						mBrowser.application.alert(successAlert);
					}
				} else {
					if (failAlert != null && !failAlert.trim().equals("")) {
						mBrowser.application.alert(failAlert);
					}
				}
			}
		});
		return true;
	}
	public boolean set(String path) {
		Drawable drawable = RexseeDrawable.getDrawable(mBrowser, path, null);
		if (drawable == null) return false;
		if (drawable instanceof BitmapDrawable) {
			WallpaperManager manager = WallpaperManager.getInstance(mBrowser.getContext());
			try {
				manager.setBitmap(((BitmapDrawable) drawable).getBitmap());
				return true;
			} catch (Exception e) {
				mBrowser.exception(getInterfaceName(), e);
				return false;
			}
		} else {
			return false;
		}
	}
	public boolean clear() {
		WallpaperManager manager = WallpaperManager.getInstance(mBrowser.getContext());
		try {
			manager.clear();
			return true;
		} catch (Exception e) {
			return false;
		}
	}
	public String getDesiredMinimumSize() {
		WallpaperManager manager = WallpaperManager.getInstance(mBrowser.getContext());
		int w = manager.getDesiredMinimumWidth();
		if (w < 0) w = mBrowser.application.screenWidth;
		int h = manager.getDesiredMinimumHeight();;
		if (h < 0) h = mBrowser.application.screenHeight;
		String rtn = "{";
		rtn += "\"width\":" + w;
		rtn += ",\"height\":" + h;
		rtn += "}";
		return rtn;
	}

}
